<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \Justmd5\PinDuoDuo\PinDuoDuo;
use Storage;

class HomeController extends Controller {
	/**
	 * Show the application dashboard.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function getIndex(Request $req) {
		return view('welcome');
	}
	public function getPddAuth(Request $req)
	{
		$config = [
			'client_id'    => '5b6b64a5ea0d450d84995b0dfc55f9d2',
			'client_secret' => '22767be297ebd9387601e3316b66f3484fcc8723',
			'debug'              => true,
			'member_type'        => 'LOGISTICS', //用户角色 ：MERCHANT(商家授权),H5(移动端),多多进宝推手(JINBAO),快团团团长(KTT),拼多多电子面单用户(LOGISTICS)
			'redirect_uri'       => 'https://qingshanerp.shanmuzhi.com/pddcallback',
		];
		// $pinduoduo = new PinDuoDuo($config);
		// 获取授权 URL
		// $url = $pinduoduo->pre_auth->authorizationUrl();
		// 重定向到授权页面
		// $pinduoduo->pre_auth->authorizationRedirect();
		// dd($url);
		// $result   = $pinduoduo->api->request('pdd.logistics.companies.get');
		// $result   = $pinduoduo->api->request('pdd.ddk.goods.detail', ['goods_id_list' => ['395581006']]);
		$redirect_uri = 'http://qingshanerp.shanmuzhi.com/pddcallback';
		$client_id = '5b6b64a5ea0d450d84995b0dfc55f9d2';
		$url = "https://fuwu.pinduoduo.com/service-market/auth?response_type=code&client_id=" . $client_id . "&redirect_uri=" . $redirect_uri . "&state=1";
		return redirect($url);
		// dd($result);
	}
	public function getPddCallback(Request $req)
	{
		// 43f9d305fda94cd3872855fd67ab3cf99193eb2c
		// access_token : 29d9562ab0bf41bf865bec328cc41b4ac7334b8b
		// $code = $req->input('code');
		// // 授权
		// $params['code'] = $code;
		// $url = $this->request('pdd.pop.auth.token.create',$params);
		// dd($url);
		// 订单
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $url = $this->request('pdd.goods.list.get',$params);
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $params['timestamp'] = strval(time());
		// // 单独参数
		// $params['is_lucky_flag'] = 0;
		// $params['order_status'] = 1;
		// $params['start_updated_at'] = strval(time() - 30*60);
		// $params['end_updated_at'] = strval(time());
		// $params['page_size'] = 10;
		// $params['page'] = 1;
		// $params['refund_status'] = 5;
		// $params['trade_type'] = 0;
		// $url = $this->request('pdd.order.number.list.increment.get', $params);
		// dd($url);
		// 电子面单
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $params['timestamp'] = strval(time());
		// $url = $this->request('pdd.waybill.search', $params);
		// dd($url);
		// 面单模板
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $params['timestamp'] = strval(time());
		// $params['wp_code'] = 'DB';
		// $url = $this->request('pdd.cloudprint.stdtemplates.get', $params);
		// dd($url);
		//   "standard_template_name" => "快递一联单"
		//   "standard_template_url" => "https://file-link.pinduoduo.com/db_one"
		//   "standard_waybill_type" => 3
		//   "standard_template_id" => 56
		// 打印机
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $params['timestamp'] = strval(time());
		// $url = $this->request('pdd.cloudprint.portableprinter.get', $params);
		// dd($url);
		// "portableprinter_name" => "QR-488BT"
        // "remark" => ""
        // "brand" => "启锐"
        // "protocol_name" => "TSPL"
		// 请求面单号
		// $params['access_token'] = 'a5d63ca49dec4f51a00459afa3f58d2bd16722e7';
		// $params['timestamp'] = strval(time());
		// // 物流公司Code
		// $wp_code = 'DB';
		// // 发货人信息
		// $sender = [
		// 	'name'=>'张先生',
		// 	'mobile' => '13908897823',
		// 	'address'=>[
		// 		'province' => '河北省',
		// 		'city'=> '衡水市',
		// 		'district' => '桃城区',
		// 		'detail' => '邓庄中学对过',
		// 	]
		// ];
		// // 请求面单信息，数量限制为10
		// $trade_order_info_dtos = [
		// 		[
		// 		'object_id'=>time(),
		// 		'template_url'=> 'https://file-link.pinduoduo.com/db_one',
		// 		'user_id'=>1,
		// 		'order_info'=>[
		// 			'order_channels_type'=> 'PDD',
		// 			'trade_order_list'=>['210628-142920960772638'],
		// 		],
		// 		'package_info'=>[
		// 			'items'	=>	[
		// 				[
		// 					'count'=>1,
		// 					'name'=> '88*58 蓝塑料 6寸金胶',
		// 				]
		// 			]
		// 		],
		// 		'recipient' =>[
		// 			'name' => '杜小宝',
		// 			'mobile' => '18900001212',
		// 			'address' => [
		// 				'province' => '河北省',
		// 				'city' => '衡水市',
		// 				'district' => '桃城区',
		// 				'detail' => '邓庄中学对过',
		// 				'town' => '对面',
		// 			]
		// 		]
		// 	]
		// ];
		// $params['param_waybill_cloud_print_apply_new_request'] = ['sender'=> $sender, 'wp_code'=> $wp_code, 'trade_order_info_dtos'=> $trade_order_info_dtos];
		// $url = $this->request('pdd.waybill.get', $params);
		// dd($url);
		// array:1 [▼
		// 	"pdd_waybill_get_response" => array:2 [▼
		// 		"request_id" => "16248751374476726"
		// 		"modules" => array:1 [▼
		// 		0 => array:3 [▼
		// 			"print_data" => "{"encryptedData":"a67d4819d0cd21554e9437e0bc2caa629864b0effd1aec65833023f78e93733ca9eec3468dc487b24682b9d64f176ca6504307461a33a112a71b2c1be2423de3a1d7ecdb81adba0ba405fca92cc5b1c814aaf39ae019f8fc00a1dec2b57516b0343692ef81a5f15638fa0bcef04bae8626d146d21a4e58b83bb1cfac198901e9b70bd049b8f9df8b4e58efdc06d8a25e07faf58bbfc8ace3d19088b8bbecf7b0d5a45cde7de8ef5096d1b147f5d01b9af7b6799bcf45c9ecd4ce0e8762177c082d3fde66c6ce4db98549a77360a9bf86ad78ad362b1586f71845c44585fd285ef3283f32ef9fd9976307a9b1f8c57335e02f3b5abcdca3e665f90dcf8578f35cf4b4fc577a8bf3201128b8e33c92642c785fae9e3db1885218ee686cc375401c62d180d1b003ccbf25b5d7ee664b5bf64081af153942ecfe9206dd6b99b7950d752d2c6ab3ed11dde4bff04c23f80f1b9b02d91ba995e81049f9b07fa9498c7ec09995055f3721189cd2b2ca77c8132ce34a300d172abbef240403de1edbdc6d01773339ca98d5e306ff18042640867602c2a3d4296f9b55e8f0153a280ae733f4a88abf8480d3e6b55b373dd06bc90d41b5fa76947f5fff499f31cb8f3853555a041cc368fda4ea7bae7bc84b1fc8ad398963c4aaf00a2e678f431f8ce4c93d78e135fc6cfbf4c10350561908e8affc7f7c30241f417af60020937d9f0679a4bf90ed8e0f732e2cd9331036b9aaea51dd3819c0b68e198cd91b65133cb1521817b82cf5751c8a75fd13b6d3c1cd5bc049cd82d6485af38595eb9049cf78eb95e463ca58d9e0b2f6a6ec33b6481e92226794233af3c01ea979e7e2fbc70912dca2d81bc2424666bae56b91a928ddf8b0d1982439b7e8cc0c272d246c2c7dd421a02b170db32ad336bd0899f4eb441148d755b89c098871995323c9b8e2dacea28496073948cca5941c6e410be95bc089846fe8f33ce03e737706457f3baea57588308ef6e60c268cc18ead9687b891bf901a5c17801fb2567500f0055b6729b60a2d6a90e60ab5dc1285cf3b0bc9324dcbe7f5ac268caa8078ea97fca1c3c7c6d07f1106ac7459c327ffc9d99a61fd192b3efe535eab48e57183ef4b2712eff40f17b92857f3a556a300d7fb2f691fb3574212fee91e258210f0b16f75effaa17588dd05e62e6a0523329fc45f5f9d6d888716c0b72980e8afa3dc93249f6fddadf78a7af3847f7cda19a8138ff7768bea7d7a6d6a6ac8c9565da1f4b9e899e584a20ef1a6905cece1f20de1eb84a0b521dae33bd8d78eb8704982d62b83699d","signature":"D+lBjEEQeEAXA6S7qL7PfljZWYJee40zF0WMn2wq7taN9Y/CH1rX+Ch8EY2Ph3wN+GYbfqBjNb7wh8KARLdAfxCDJx4OatXhkwZeMVo1Sh27YWVW2Hk1yDid5ZSEo2i5eE0DqrbC/iXQAc10w+hSyogHN9VRCyltzFzGXDX9C6I=","templateUrl":"https://file-link.pinduoduo.com/db_one","ver":"3"}"
		// 			"waybill_code" => "DPK368062829273"
		// 			"object_id" => "1624875137"
		// 		]
		// 		]
		// 	]
		// 	]

		// array:1 [▼
		//   "pop_auth_token_create_response" => array:18 [▼
		//     "refresh_token_expires_in" => 86386
		//     "w1_expires_in" => 1624935501
		//     "owner_name" => "pdd62521972682"
		//     "owner_id" => "625219726"
		//     "w2_expires_at" => 1624935501
		//     "r2_expires_at" => 1624935501
		//     "access_token" => "a5d63ca49dec4f51a00459afa3f58d2bd16722e7"
		//     "refresh_token" => "3e2bf0834c354ffd915b9060b6e948a8c3cfc604"
		//     "w2_expires_in" => 86386
		//     "refresh_token_expires_at" => 1624935501
		//     "expires_at" => 1624935501
		//     "r1_expires_in" => 86386
		//     "scope" => array:217 [▶]
		//     "w1_expires_at" => 1624935501
		//     "r2_expires_in" => 86386
		//     "r1_expires_at" => 1624935501
		//     "expires_in" => 86386
		//     "request_id" => "16248491142147194"
		//   ]
		// ]
	}

	/**
	 * @param $params
	 *
	 * @return string
	 */
	private function signature($params)
	{
		ksort($params);
		$paramsStr = '';
		array_walk($params, function ($item, $key) use (&$paramsStr) {
			if ('@' != substr($item, 0, 1)) {
				$paramsStr .= sprintf('%s%s', $key, $item);
			}
		});
		$client_secret = '22767be297ebd9387601e3316b66f3484fcc8723';
		return strtoupper(md5(sprintf('%s%s%s', $client_secret, $paramsStr, $client_secret)));
	}

	/**
	 * @param string $method
	 * @param array  $params
	 * @param string $data_type
	 *
	 * @return mixed
	 */
	public function request($method, $params = [], $data_type = 'JSON')
	{
		$config = [
			'client_id'    => '5b6b64a5ea0d450d84995b0dfc55f9d2',
			'client_secret' => '22767be297ebd9387601e3316b66f3484fcc8723',
			'member_type'        => 'LOGISTICS', //用户角色 ：MERCHANT(商家授权),H5(移动端),多多进宝推手(JINBAO),快团团团长(KTT),拼多多电子面单用户(LOGISTICS)
			'redirect_uri'       => 'https://qingshanerp.shanmuzhi.com/pddcallback',
		];
		$params = $this->paramsHandle($params);
		$params['client_id'] = '5b6b64a5ea0d450d84995b0dfc55f9d2';
		$params['sign_method'] = 'md5';
		$params['type'] = $method;
		$params['data_type'] = $data_type;
		$params['timestamp'] = strval(time());
		$params['sign'] = $this->signature($params);
		dump($params);
		// https://gw-api.pinduoduo.com/api/router?type=pdd.pop.auth.token.create&data_type=JSON&client_id=5b6b64a5ea0d450d84995b0dfc55f9d2&code=43f9d305fda94cd3872855fd67ab3cf99193eb2c&timestamp=1624848369&sign=B024CCA7179AF0BDFF8E229002BC06DE
		// return $params;
		$url = 'https://gw-api.pinduoduo.com/api/router';
		$res = $this->postCurl($url, $params);
		dd($res);
	}
	// 请求接口用的CURL功能
	public function postCurl($url, $body, $type = "POST", $json = 0)
	{
		$header = array();
		//1.创建一个curl资源
		$ch = curl_init();
		//2.设置URL和相应的选项
		curl_setopt($ch, CURLOPT_URL, $url); //设置url
		//1)设置请求头
		if ($json) {
			array_push($header, 'Content-Type:application/json');
		} else {
			array_push($header, 'Content-Type:application/x-www-form-urlencoded;charset=utf-8');
		}
		//设置请求头
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		//设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时限制防止死循环
		//设置发起连接前的等待时间，如果设置为0，则无限等待。
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		//将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		//上传文件相关设置
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算

		//3)设置提交方式
		switch ($type) {
			case "GET":
				curl_setopt($ch, CURLOPT_HTTPGET, true);
				break;
			case "POST":
				curl_setopt($ch, CURLOPT_POST, true);
				break;
			case "PUT": //使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请 求。这对于执行"DELETE" 或者其他更隐蔽的HTT
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
				break;
			case "DELETE":
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
				break;
		}

		//2)设备请求体
		if (count($body) > 0 && $type == 'POST') {
			// $body = $json ? json_encode($body) : $body;
			$postFields = http_build_query($body);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); //全部数据使用HTTP协议中的"POST"操作来发送。
		}

		//3.抓取URL并把它传递给浏览器
		$res = curl_exec($ch);
		$result = json_decode($res, true);
		//4.关闭curl资源，并且释放系统资源
		curl_close($ch);
		if (empty($result)) {
			return $res;
		} else {
			return $result;
		}
	}

	/**
	 * @param array $params
	 *
	 * @return array
	 */
	protected function paramsHandle(array $params)
	{
		array_walk($params, function (&$item) {
			if (is_array($item)) {
				$item = json_encode($item);
			}
			if (is_bool($item)) {
				$item = ['false', 'true'][intval($item)];
			}
		});

		return $params;
	}
}
